package com.easou.ps.master.lbs;

import java.net.HttpURLConnection;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.log4j.Logger;

import com.easou.ps.exec.Executor;
import com.easou.ps.exec.ExecutorBuilder;
import com.easou.ps.master.kit.ConfigFactory;
import com.easou.ps.master.util.HttpClientTools;
/**
 * 获取lbs结果
 * @author Administrator
 *
 */
public class RequestLBSClient {
	private static Logger LOG = Logger.getLogger("query");

	private static Executor<LbsResponse> executor;
	private static String[] addresses;
	private static List<String> aliveAddresses = new ArrayList<String>();
	private static List<String> deadAddresses = new ArrayList<String>();
	private static AtomicInteger counter = new AtomicInteger(0);
	private static DetectThread detectThread = new DetectThread();
	static {
		try {
			int errcorrectApiThreads = ConfigFactory.getSysConfig().getInt("lbs.api.threads", 200);
			int maxApiThreads = ConfigFactory.getSysConfig().getInt("lbs.api.max.threads", 400);
			int errcorrectApiTimeout = ConfigFactory.getSysConfig().getInt("lbs.api.timeout", 1000);
			executor = new ExecutorBuilder<LbsResponse>("LBS").setCoreSize(errcorrectApiThreads).setMaxSize(maxApiThreads).setTimeout(errcorrectApiTimeout).toExecutor();
			String[] addresses = ConfigFactory.getSysConfig().gets("lbs.api.address");
			if (addresses == null) {
				addresses = new String[0];
				LOG.error("no config option: lbs.api.address");
			}
			RequestLBSClient.addresses = addresses;
			for (String address : addresses) {
				aliveAddresses.add(address);
			}
			detectThread.start();
		} catch (Exception e) {
			LOG.info("error initialize RequestLBSClient", e);
		}
	}
	
	private static String getAddress() {
		int num = counter.getAndIncrement();
		if (aliveAddresses.size() > 0) {
			int idx = num % aliveAddresses.size();
			String address = aliveAddresses.get(idx);
			return address;
		}
		return null;
	}
	public static LbsResponse getResult(){
		LbsResponse response = null;
		List<LbsResponse> wordList = executor.getResults();
		if (wordList != null && wordList.size() > 0) {
			response = wordList.get(0);
		}
		return response;
	}
	
	public static void pushTask(final String paramStr,final String query) {
		try {
			final String address = getAddress();
			if (address != null) {
				executor.prepare();
				executor.execTask(new Callable<LbsResponse>() {
					@Override
					public LbsResponse call() throws Exception {
						try {
							long startTime = System.currentTimeMillis();
							String wholeURL = MessageFormat.format(address, paramStr);
							String jsonResult = HttpClientTools.getHttpResPonseBody(wholeURL, "UTF-8");
							LbsResponse result = new LbsResponse(wholeURL,jsonResult);
							int cost = (int) (System.currentTimeMillis() - startTime);
							result.setCostTime(cost);
							return result;
						} catch (Exception e){
							LOG.error("invoke correct api error", e);
						}
						return null;
					}
				});
			}
		} catch (Exception e) {
			LOG.error("error com.easou.ps.master.channel.RequestLBSClient", e);
		}
	}
	
	static class DetectThread extends Thread {
		private int DETECT_RETRY_TIMES = 3;
		private int RETRY_INTERVAL_MILLIS = 200;
		private int DETECT_INTERVAL_MILLIS = 5000;
		
		public void run() {
			while (true) {
				try {
					for (String address : RequestLBSClient.addresses) {
						boolean active = false;
						for (int k = 0; k < DETECT_RETRY_TIMES; k++) {
							if (isHttpActive(address)) {
								active = true;
								break;
							}
							Thread.sleep(RETRY_INTERVAL_MILLIS);
						}
						if (active) {
							if (!RequestLBSClient.aliveAddresses.contains(address)) {
								RequestLBSClient.aliveAddresses.add(address);
								RequestLBSClient.deadAddresses.remove(address);
							}
						} else {
							if (!RequestLBSClient.deadAddresses.contains(address)) {
								RequestLBSClient.aliveAddresses.remove(address);
								RequestLBSClient.deadAddresses.add(address);
							}
						}
					}
					Thread.sleep(DETECT_INTERVAL_MILLIS);
				} catch (Exception e) {
					LOG.error("RequestLBSClient detecting thread meeting an upexpected exception:" + e.getMessage(), e);
				}
			}
		}
		private boolean isHttpActive(String httpUrl) {
			try {
				HttpURLConnection url = (HttpURLConnection) new URL(httpUrl).openConnection();
				url.connect();
				url.disconnect();
				return true;
			} catch (Exception e) {
				LOG.error("exception detected on error correct api:" + httpUrl + ", exception:" + e.getMessage());
				return false;
			}
		}
	}
}
